﻿using System.Collections.Generic;
using Myotragus.Data.Tupples.Tests.Domain;
using NHibernate;
using NUnit.Framework;

namespace Myotragus.Data.Tupples.Tests
{
	/*
	 Execute only to prepara the database. Methods here would create data
	 */
	[TestFixture]
	public class PrepareDataBase
	{
		[Test]
		public void AssignCategories()
		{
			using (var session = Core.OpenSession())
			{
				var products = session.CreateCriteria<Product>().List<Product>();
				var categories = session.CreateCriteria<Category>().List<Category>();

				foreach (var p in products)
				{
					for (var i = 0; i < Core.GetRandom(5); i++)
						AssignCategory(session, p, categories);
				}

				session.Flush();
			}
		}

		[Test]
		public void ClearCategoryAssignment()
		{
			using (var session = Core.OpenSession())
			{
				var associations = session.CreateCriteria<CategoryProducts>().List<CategoryProducts>();
				foreach (var assoc in associations)
					session.Delete(assoc);

				session.Flush();
			}
		}

		private static void AssignCategory(ISession session, Product product, IList<Category> categories)
		{
			var c = categories[Core.GetRandom(categories.Count)];
			using (var transaction = session.BeginTransaction())
			{
				var categoryProduct = new CategoryProducts
				{
					ProductId = product.Id,
					CategoryId = c.Id,
					CustomDescription = Core.GenerateSentence()
				};

				if (session.Get<CategoryProducts>(categoryProduct.Key) == null)
					session.Save(categoryProduct);

				transaction.Commit();
			}
		}

		[Test]
		public void InsertProducts()
		{
			using (var session = Core.OpenSession())
			{
				for (var i = 0; i < 100; i++)
				{
					var p = new Product { Name = Core.GenerateSentence(3) };
					using (var transaction = session.BeginTransaction())
					{
						session.Save(p);
						transaction.Commit();
					}
				}

				session.Flush();
			}
		}

		[Test]
		public void InsertCategories()
		{
			using (var session = Core.OpenSession())
			{
				for (var i = 0; i < 10; i++)
				{
					var p = new Category { Name = Core.GenerateSentence(1) };
					using (var transaction = session.BeginTransaction())
					{
						session.Save(p);
						transaction.Commit();
					}
				}

				session.Flush();
			}
		}
	}
}
